<template>
  <y-layout-base class="menu wh-full" title="菜单管理">
    <template #header>
      <a-button type="primary" @click="handleAdd">添加菜单</a-button>
    </template>
    <y-config-table
     ref="configTableRef"
      :columns="columns"
      :data-request="getMenuPage"
      :page="true"
      :tree="true"
    />
  </y-layout-base>
</template>
<script setup>
defineOptions({
  name: 'Menu',
});
import { getMenuPage } from '@/api/menu';
import { baseColumns } from './columns';
import editMenuModal from './editMenuModal.vue';
// import { useFormModal } from '@/hooks/modal/useFormModal';
import { getAllMenus, saveMenu, deleteMenu, getMenuDetail } from '@/api/menu';
import { buildTree } from "@/utils/buildTree";
import { DeviceTypeEnum } from '@/constants/enums/menuEnums.js';
import {useFormModal,useConfirm,message} from '@/hooks/modal';


const {openModal} = useFormModal();
const {warning} = useConfirm();


const initForm = {
  id:null,
  type:'menu',
  title:"",
  name:"",
  path:"",
  component:"",
  deviceType:DeviceTypeEnum.DESKTOP,
  icon:"",
  sort:0,
  show: 1,
  keepAlive: 1,
  status: 0,// 1：正常，0：停用
}
let menuTree = [];
const configTableRef = ref(null);
const loadMenus = async () => {
  try {
    const response = await getAllMenus();
    const flatData = Array.isArray(response) ? response : response.data || [];
    menuTree = buildTree(flatData);
  } catch (error) {

  } finally {
  }
};
loadMenus();
const refreshTable = ()=>{
  configTableRef.value.refresh();
}
const open = (row)=>{
  openModal(editMenuModal,{formState:row,menuTree}).then(async menu=>{
    if(menu){
      if(menu.parentId === undefined){
        menu.parentId = null;
      }
      await saveMenu(menu);
      message.success('保存成功');
      refreshTable();
      loadMenus();
    }
  })
}
// 添加菜单
const handleAdd = ()=>{
  open(initForm)
}
// 添加子菜单
const handleAddChild = ({record}) => {
  open({
    ...initForm,
    parentId:record.id,
  })
};
// 编辑菜单
const handleEdit = ({record}) => {
  open(record)
};
// 删除菜单
const handleDelete = async ({record}) => {
  warning(`确认删除菜单${record.title}吗？删除后不可恢复！`).then(async ()=>{
    await deleteMenu(record.id);
    message.success('删除成功');
    refreshTable();
    loadMenus();
  })
};

const columns = [
  ...baseColumns,
  {
    title: '操作',
    dataIndex: 'action',
    width:210,
    actions: [
      {
        label: '编辑',
        type: 'link',
        size: 'small',
        danger:true,
        onClick: handleEdit,
      },
      {
        label: '添加子菜单',
        type: 'link',
        size: 'small',
        danger:true,
        onClick: handleAddChild,
      },
      {
        label: '删除',
        type: 'link',
        size: 'small',
        danger:true,
        onClick: handleDelete,

      }
    ],
  },
];
</script>
